package com.jandan.web.front;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.jandan.logic.JWordzFacade;
import com.jandan.ui.client.util.ClientUtil;
import com.jandan.ui.model.BlogArticle;

public class BlogController extends MultiActionController {
	private JWordzFacade jwordz;

	public void setJwordz(JWordzFacade jwordz) {
		this.jwordz = jwordz;
	}

	public ModelAndView all(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String categoryID = request.getParameter("categoryID");
		String category = ClientUtil.BLOG_CATEGORIES[0];

		if (categoryID != null) {
			int c = Integer.parseInt(categoryID);
			category = ClientUtil.BLOG_CATEGORIES[c];
		}

		String pageIndex = request.getParameter("pageIndex");
		int pi = ClientUtil.FIRST_PAGE_INDEX;
		int limit = ClientUtil.ARITCLE_PAGE_LIMIT;
		if (pageIndex != null) {
			pi = Integer.parseInt(pageIndex);
		}

		int totalArticleCount = jwordz.getTotalBlogArticleCountByCategory(category);
		List<BlogArticle> articleList = jwordz.getAllBlogArticleListByCategory(pi * limit, limit,category);
		if (articleList == null) {
			articleList = new ArrayList<BlogArticle>();
		}

		Map map = new HashMap();
		map.put("totalArticleCount", totalArticleCount);
		map.put("articleList", articleList);
		map.put("categoryID", categoryID);
		
		return new ModelAndView("blog",map);
	}

	public ModelAndView one(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String articleID = request.getParameter("articleID");
		String categoryID = request.getParameter("categoryID");
		
		if(articleID != null){
			long l = Long.parseLong(articleID);
			BlogArticle article = jwordz.getBlogArticleByArticleID(l);
			Map map = new HashMap();
			map.put("article", article);
			map.put("categoryID", categoryID);
			
			return new ModelAndView("blogcontent",map); 
		}
		return null;
	}
}
